import Storage from '@/untils/storage.js'
const cart = {
	state() {
		return {
			goodsNumber: 0,
			cart: [
				//{
				   // attr_id: "0",
				   // goods_descript: "美丽雅 斜口收纳箱大号 加厚衣物儿童玩具整理箱 塑料家用药品储物箱 厨房客厅车载翻盖收纳柜三色42L 3个美丽雅 斜口收纳箱大号 加厚衣物儿童玩具整理箱 塑料家用药品储物箱 厨房客厅车载翻盖收纳柜三色42L 3个美丽雅 斜口收纳箱大号 加厚衣物儿童玩具整理箱 塑料家用药品储物箱",
				   // goods_id: "637f2853819ce8662200551b",
				   // goods_name: "收纳箱",
				   // num: 1,
				   // price: 14990,
			       // thumn: "https://img10.360buyimg.com/n1/jfs/t1/199816/17/30315/61677/637d853cE120696f0/d1ea6626d7b06f94.jpg.avif"
			    //},
			]
		}
	},
	mutations: {
		addGoods(state, goods) {
            goods.checked = false;
			//判断一下cart中是否已经有这个商品了
			if (state.cart.length == 0) {
				state.cart.push(goods)
			} else {
				//循环以后商品不存在我们怎么判断
				let isHas = false; //默认false表示购物车中不存在该商品
				for (let i = 0; i < state.cart.length; i++) {
					const cartElem = state.cart[i];
					if (goods.goods_id == cartElem.goods_id && goods.attr_id == cartElem.attr_id) {
						state.cart[i].num++; //判断出商品已经存在 那购买数量增加1
						isHas = true;
					}
				}
				if (!isHas) {
					state.cart.push(goods)
				}
			}
			//将添加好的商品存储到缓存中
			Storage.set('cartGoods',state.cart);
		},
		setGoodsChecked(state,index){
			//将商品锁定状态改为相反
			state.cart[index].checked = !state.cart[index].checked;
		    Storage.set('cartGoods',state.cart);
		},
		addGoodsNum(state,index){
			state.cart[index].num++;
			Storage.set('cartGoods',state.cart);
		},
		subGoodsNum(state,index){
			if(state.cart[index].num > 1){
			   state.cart[index].num--;
			}
			Storage.set('cartGoods',state.cart);
		},
        changeCartChecked(state,statue){
			for (let i = 0; i < state.cart.length; i++) {
				state.cart[i].checked = !statue;
			}
			Storage.set('cartGoods',state.cart);
		},
		storageToCart(state,goodscart){
			state.cart = goodscart
		},
	},
	actions: {

	},
	getters:{
		cartGoodsNumber(state){
			let countGoodsNum = 0;
			for (let i = 0; i < state.cart.length; i++) {
				let cartElem = state.cart[i];
			    countGoodsNum += cartElem.num;
			}
			return countGoodsNum;
		},
		cartGoodsTotal(state){//计算购物车选中商品总价
			let total = 0;
			for (let i = 0; i < state.cart.length; i++) {
				let cartElem = state.cart[i];
				if(cartElem.checked){
					total += cartElem.num*cartElem.price
				}
			}
			return total;
		},
		cartAllChecked(state){
			let all = false;
			let count = 0;
		    for (let i = 0; i < state.cart.length; i++) {
		    	let cartElem = state.cart[i];
		    	if(cartElem.checked){
		    		count++;
		    	}
		    }
			if(state.cart.length == count){
				all = true
			}
			if(state.cart.length == 0){
				all = false
			}
			return all;
		}
	}
}
export default {
	cart
}
